﻿// <copyright file="MainWindow.xaml.cs" company="Robert Venables">
// Copyright (c) 2009 Robert Venables.
// </copyright>
// <author>Robert Venables</author>
// <email>rob@rvenables.com</email>

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using VNotify;

namespace VNotifyWPFExample
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// Holds the interface sending message state.
        /// </summary>
        private bool _InterfaceSending = false;

        /// <summary>
        /// Initializes a new instance of the MainWindow class.
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Gets a value indicating whether the interface
        /// is currently sending a message.
        /// </summary>
        public bool InterfaceSending
        {
            get
            {
                return this._InterfaceSending;
            }

            private set
            {
                this._InterfaceSending = value;

                if (this._InterfaceSending == true)
                {
                    this.DisplaySendingAnimation();
                }
                else
                {
                    this.HideSendingAnimation();
                }

                this.Message.IsEnabled = !this._InterfaceSending;
                this.APIKey.IsEnabled = !this._InterfaceSending;
                this.Send.IsEnabled = !this._InterfaceSending;
                this.RememberAPIKey.IsEnabled = !this._InterfaceSending;
            }
        }

        /// <summary>
        /// Displays the sending animation.
        /// </summary>
        private void DisplaySendingAnimation()
        {
            Stream animationStream
                = App.GetResourceStream(
                    new Uri("/Images/Sending.gif", UriKind.Relative)).Stream;

            Bitmap animation = new System.Drawing.Bitmap(animationStream);
            SendingAnimation.Image = animation;
        }

        /// <summary>
        /// Hides the sending animation.
        /// </summary>
        private void HideSendingAnimation()
        {
            SendingAnimation.Image = null;
        }

        /// <summary>
        /// Validates a given API key and message. Displays a descriptive 
        /// messagebox if the validation fails for any reason.
        /// </summary>
        /// <param name="apiKey">The API key used to identify the recipient.</param>
        /// <param name="message">The notification message to send.</param>
        /// <returns>True if both API key and message are valid.</returns>
        private bool UserInputValid(string apiKey, string message)
        {
            if (string.IsNullOrEmpty(apiKey) || apiKey.Length < 4)
            {
                MessageBox.Show(
                    "Ooops... That doesn't look  like a valid API Key.\n" +
                    "Please enter a valid API key.",
                    "Invalid API Key",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);

                return false;
            }

            if (string.IsNullOrEmpty(message))
            {
                MessageBox.Show(
                    "Please enter a message to send.",
                    "No Message To Send",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);

                return false;
            }

            return true;
        }

        private void Send_Click(object sender, RoutedEventArgs e)
        {
            string apiKeyValue = this.APIKey.Text;
            string messageValue = this.Message.Text;

            if (this.UserInputValid(apiKeyValue, messageValue) == false) return;

            this.InterfaceSending = true;

            AppNotificationClient client = new AppNotificationClient();
            AppNotificationRecipient recipient = new AppNotificationRecipient(apiKeyValue);
            AppNotification notification = new AppNotification(messageValue);

            IAsyncResult asyncToken = null;

            AsyncCallback onFinished = delegate 
            {
                try
                {
                    this.Dispatcher.Invoke(
                        (System.Windows.Forms.MethodInvoker)delegate
                    {
                        this.InterfaceSending = false;
                    });

                    client.EndSend(asyncToken);
                }
                catch
                {
                    MessageBox.Show(
                     "Ooops... Failed to send notification.\n" +
                     "Please double check your API Key.",
                     "Send Failed",
                     MessageBoxButton.OK,
                     MessageBoxImage.Error);
                }
            };

            asyncToken = client.BeginSend(notification, recipient, onFinished);
        }

        private void PrimaryWindow_Loaded(object sender, RoutedEventArgs e)
        {
            this.RememberAPIKey.IsChecked = Properties.Settings.Default.RememberAPIKey;

            if (Properties.Settings.Default.RememberAPIKey)
            {
                this.APIKey.Text = Properties.Settings.Default.LastAPIKey;
            }
        }

        private void PrimaryWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Properties.Settings.Default.RememberAPIKey = this.RememberAPIKey.IsChecked.Value;

            if (Properties.Settings.Default.RememberAPIKey)
            {
                Properties.Settings.Default.LastAPIKey = this.APIKey.Text;
            }

            Properties.Settings.Default.Save();
        }
    }
}
